﻿namespace HabraReader
{
    using System;
    using System.Collections.Specialized;
    using System.Collections;
    using System.Drawing;
    using System.IO;
    using System.Windows.Forms;
    using Classes;

    public partial class MainForm : Form
    {
        private AboutForm          AboutWindow;
        private PreferencesForm    PreferencesWindow;
        private InfoForm           InformationWindow;
        private StringDictionary[] Articles;
        private StringDictionary[] Blogs;
        private int                BeforeCollapseSize; // Размер панели до сворачивания
        private bool               TreeViewCollapsed; // Панель свернута или нет
        private StringDictionary   PrivateOptionsDictionary; // Текущие настройки программы
        private StringDictionary   Images = new StringDictionary();
        private string             Path;

        public MainForm()
        {
            InitializeComponent();
        }

        private void InitImages()
        {
            Images.Add("Дизайн",  "2");
            Images.Add("Article", "3");
            Images.Add("PHP",     "4");
            Images.Add("Ассемблер", "6");
            Images.Add("Каскадные Таблицы Стилей", "5");
            Images.Add(".NET", "7");
            Images.Add("nVidia CUDA", "8");
        }

        public StringDictionary OptionsDictionary // Accessor для PrivateOptionsDictionary
        {
            get
            {
                return PrivateOptionsDictionary;
            }
            set
            {
                PrivateOptionsDictionary = value;
            }
        }

        private void CheckWindowOptions()
        {
            PrivateOptionsDictionary["WindowState"]      = WindowState.ToString();
            PrivateOptionsDictionary["WindowWidth"]      = Width.ToString();
            PrivateOptionsDictionary["WindowHeight"]     = Height.ToString();
            PrivateOptionsDictionary["WindowPosition.X"] = Location.X.ToString();
            PrivateOptionsDictionary["WindowPosition.Y"] = Location.Y.ToString();
            PrivateOptionsDictionary["SplitterDistance"] = SplitContainer.SplitterDistance.ToString();
        }

        private void AboutMenuItemClick(object sender, EventArgs e) // Показать "О программе"
        {
            AboutWindow = new AboutForm();
            AboutWindow.ShowDialog();
        }

        private void CollapseButtonClick(object sender, EventArgs e)
        {
            if (TreeViewCollapsed)
            {
                TreeViewCollapsed = false;
                SplitContainer.IsSplitterFixed = false;
                SplitContainer.SplitterDistance = BeforeCollapseSize;
            }
            else
            {
                TreeViewCollapsed = true;
                SplitContainer.IsSplitterFixed = true;
                BeforeCollapseSize = SplitContainer.SplitterDistance;
                SplitContainer.SplitterDistance = 12;
            }
        }

        private void ExitMenuItemClick(object sender, EventArgs e) // Выход
        {
            Application.Exit();
        }

        private void MainFormClosed(object sender, FormClosedEventArgs e)
        {
            CheckWindowOptions();
            Options.WriteOptions(PrivateOptionsDictionary);
            if (Directory.Exists(@"temp")) Directory.Delete(@"temp", true);
        }

        private void MainFormLoad(object sender, EventArgs e)
        {
            InitImages();
            GetAppPath();

            // Если файла с настройками нет, то пишем их по дефолту
            if (!File.Exists("options.xml"))
            {
                Options.WriteDefaultOptions();
            }

            // Читаем настройки
            PrivateOptionsDictionary = Options.ReadOptions();

            // Положение окна на экране
            var windowPosition = new Point
                {
                    X = Int32.Parse(PrivateOptionsDictionary["WindowPosition.X"]),
                    Y = Int32.Parse(PrivateOptionsDictionary["WindowPosition.Y"])
                };
            Location = windowPosition;

            // Состояние окна
            WindowState = (FormWindowState)Enum.Parse(typeof(FormWindowState), 
                    PrivateOptionsDictionary["WindowState"]);

            // Размер окна
            Width  = Int32.Parse(PrivateOptionsDictionary["WindowWidth"]);
            Height = Int32.Parse(PrivateOptionsDictionary["WindowHeight"]);

            if (TreeViewCollapsed)
            {
                SplitContainer.SplitterDistance = 12;
            }
            else
            {
                SplitContainer.SplitterDistance =
                        BeforeCollapseSize = Int32.Parse(PrivateOptionsDictionary["SplitterDistance"]);
            }

            var db = new Database(PrivateOptionsDictionary["Database"]);
            db.Connect();
            var blogsCount = db.GetBlogsCount();
            if (blogsCount != 0)
            {
                Blogs = new StringDictionary[blogsCount];
                for (int i = 0; i < blogsCount; i++)
                {
                    Blogs[i] = new StringDictionary();
                }
                Blogs = db.GetBlogs();
                for (int i = 0; i < Blogs.Length; i++)
                {
                    TreeView.Nodes[0].Nodes.Add(Blogs[i]["blog_name"]);
                    TreeView.Nodes[0].Nodes[i].ImageIndex = 
                        Int32.Parse(Images[Blogs[i]["blog_name"]]);
                    TreeView.Nodes[0].Nodes[i].SelectedImageIndex = 
                        Int32.Parse(Images[Blogs[i]["blog_name"]]);
                    Articles = db.GetArticles(Int32.Parse(Blogs[i]["blog_id"]));
                    for (int j = 0; j < Articles.Length; j++)
                    {
                        TreeView.Nodes[0].Nodes[i].Nodes.Add(Articles[j]["article_name"]);
                        TreeView.Nodes[0].Nodes[i].Nodes[j].ImageIndex = 
                            Int32.Parse(Images["Article"]);
                        TreeView.Nodes[0].Nodes[i].Nodes[j].SelectedImageIndex = 
                            Int32.Parse(Images["Article"]);
                    }
                    TreeView.Nodes[0].Nodes[i].Text = Blogs[i]["blog_name"] + 
                        " (" + Articles.Length + ")"; 
                }
            }
            else
            {
                TreeView.Nodes[0].Nodes.Add("Блогов в данный момент нет");
                TreeView.Nodes[0].Nodes[0].ImageIndex = 1;
                TreeView.Nodes[0].Nodes[0].SelectedImageIndex = 1;
                TreeView.ExpandAll();
            }

            Browser.Navigate(@"file:///" + Path + "/include/welcome.html");
        }

        // Показать "Опции"
        private void OptionsMenuItemClick(object sender, EventArgs e)
        {
            PreferencesWindow = new PreferencesForm(this);
            PreferencesWindow.Show();
        }

        private void TreeViewAfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 2)
            {
                int start = e.Node.Parent.Text.LastIndexOf("(") - 1;
                int count = e.Node.Parent.Text.LastIndexOf(")") - start + 1;
                Text = "HabraReader : " + e.Node.Parent.Text.Remove(start, count) + " → " + e.Node.Text;
                Text = Text;

                string articleName = e.Node.Text;
                Database db = new Database(PrivateOptionsDictionary["Database"]);
                db.Connect();
                db.GetArticle(articleName);
                Browser.Navigate(Environment.CurrentDirectory + @"/temp/temp.html");
            }
            else
            {
                Text = "HabraReader";
            }
        }

        private void UpdateMenuItemClick(object sender, EventArgs e)
        {

        }

        private void InfoMenuItemClick(object sender, EventArgs e)
        {
            InformationWindow = new InfoForm(this);
            InformationWindow.ShowDialog();
        }

        private void GetAppPath()
        {
            ArrayList tmparray = new ArrayList();
            Path = Environment.CurrentDirectory;
            for (int i = 0; i < Path.Length; i++)
            {
                if (Path[i] == '\\')
                {
                    tmparray.Add(i);
                }
            }

            string tmpPath = "";
            int lastpos = 0;
            for (int i = 0; i < tmparray.Count; i++)
            {
                int pos = (int)tmparray[i];
                tmpPath += Path.Substring(lastpos, (int)tmparray[i] - lastpos);
                tmpPath += "/";
                lastpos = pos + 1;
            }
            tmpPath += Path.Substring(lastpos, Path.Length - lastpos);
            Path = tmpPath;
        }

        private void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
    }
}